package com.boc.langxiang.ui.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.boc.langxiang.R;
import com.boc.langxiang.contract.common.MainContract;
import com.boc.langxiang.entity.events.LogoutEvent;
import com.boc.langxiang.entity.events.NetWorkEvent;
import com.boc.langxiang.presenter.common.MainPresenter;
import com.boc.langxiang.ui.dialog.CustomAlertDialog;
import com.boc.langxiang.ui.fragment.adm.AdmListFragment;
import com.boc.langxiang.ui.fragment.customized.CustomizedFragment;
import com.boc.langxiang.ui.fragment.index.IndexFragment;
import com.boc.langxiang.ui.fragment.me.MeFragment;
import com.boc.langxiang.ui.fragment.shalo.ShaLoFragment;
import com.boc.langxiang.ui.fragment.shop.ShopFragment;
import com.boc.langxiang.ui.view.MainBottomBarItemView;
import com.boc.langxiang.util.L;
import com.boc.langxiang.util.NetUtil;
import com.boc.langxiang.util.T;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends BaseActivity implements MainContract.View {


    @BindView(R.id.index)
    MainBottomBarItemView mIndex;
    @BindView(R.id.adm)
    MainBottomBarItemView mAdm;
    @BindView(R.id.shop)
    MainBottomBarItemView mShop;
    @BindView(R.id.shalo)
    MainBottomBarItemView mShalo;
    @BindView(R.id.me)
    MainBottomBarItemView mMe;
    @BindView(R.id.customized)
    MainBottomBarItemView mCustomized;
    @BindView(R.id.bottom_bar)
    LinearLayout bottomBar;
    @BindView(R.id.content)
    FrameLayout content;

    private int lastChecked = R.id.index;
    private long exitTime;
    private Fragment lastFragment = null;
    private BroadcastReceiver mBroadcastReceiver;

    private final String TAG_FRAGMENT_INDEX = "index";
    private final String TAG_FRAGMENT_ADM = "adm";
    private final String TAG_FRAGMENT_SHOP = "shop";
    private final String TAG_FRAGMENT_SHALO = "shalo";
    private final String TAG_FRAGMENT_ME = "me";
    private final String TAG_FRAGMENT_CUSTOMIZED = "customized";
    private MainPresenter mPresenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initNetBroadcastReceiver();
        init();
        mPresenter = new MainPresenter(this);
        mPresenter.getuser();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
        }
    }

    private void init() {
        setEnabled(false, true, true, true, true);

        changeFragment(TAG_FRAGMENT_INDEX);

    }

    private void changeFragment(String tag) {
        Fragment fragment = getSupportFragmentManager()
                .findFragmentByTag(tag);
        if (fragment == null) {
            fragment = getFragmentByTag(tag);
            addFragment(fragment, tag);
        } else {
            showFragment(fragment);
        }
        lastFragment = fragment;
    }

    private Fragment getFragmentByTag(String tag) {
        if (TextUtils.isEmpty(tag)) {
            return IndexFragment.newInstance();
        }
        if (tag.equals(TAG_FRAGMENT_INDEX)) {
            return IndexFragment.newInstance();
        } else if (tag.equals(TAG_FRAGMENT_ADM)) {
            return AdmListFragment.newInstance();
        } else if (tag.equals(TAG_FRAGMENT_SHOP)) {
            return ShopFragment.newInstance();
        } else if (tag.equals(TAG_FRAGMENT_SHALO)) {
            return ShaLoFragment.newInstance();
        } else if (tag.equals(TAG_FRAGMENT_ME)) {
            return MeFragment.newInstance();
        } else if (tag.equals(TAG_FRAGMENT_CUSTOMIZED)) {
            return CustomizedFragment.newInstance();
        }
        return IndexFragment.newInstance();
    }

    private void addFragment(Fragment fragment, String tag) {
        FragmentTransaction trans = getSupportFragmentManager()
                .beginTransaction();
        if (lastFragment != null) {
            trans.hide(lastFragment);
        }
        trans.add(R.id.content, fragment, tag);
        trans.commitAllowingStateLoss();
    }

    private void showFragment(Fragment fragment) {
        FragmentTransaction trans = getSupportFragmentManager()
                .beginTransaction();
        if (lastFragment != null) {
            trans.hide(lastFragment);
        }
        trans.show(fragment);
        trans.commitAllowingStateLoss();
    }

    private void initNetBroadcastReceiver() {
        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(
                        ConnectivityManager.CONNECTIVITY_ACTION)) {
                    if (NetUtil.isConnected(mContext)) {
                        EventBus.getDefault().post(new NetWorkEvent(NetWorkEvent.AVAILABLE));
                    } else {
                        EventBus.getDefault().post(new NetWorkEvent(NetWorkEvent.UNAVAILABLE));
                    }
                }
            }
        };

        registerReceiver(mBroadcastReceiver, new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION));
    }


    private void setEnabled(boolean indexB, boolean admB, boolean customizedB, boolean shopB, boolean meB) {
        mIndex.setBarEnable(indexB);
        mAdm.setBarEnable(admB);
        mShop.setBarEnable(shopB);
        mCustomized.setBarEnable(customizedB);
        mMe.setBarEnable(meB);
    }

    @OnClick({R.id.index, R.id.adm, R.id.shop, R.id.shalo, R.id.me, R.id.customized})
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.index:
                L.i("index");
                setEnabled(false, true, true, true, true);
                if (lastChecked != R.id.index) {
                    changeFragment(TAG_FRAGMENT_INDEX);
                    lastChecked = id;
                }
                break;
            case R.id.adm:
                L.i("adm");
                setEnabled(true, false, true, true, true);
                if (lastChecked != R.id.adm) {
                    changeFragment(TAG_FRAGMENT_ADM);
                    lastChecked = id;
                }
                break;
            case R.id.customized:
                boolean login = isLogin();
                if (login) {
                    setEnabled(true, true, false, true, true);
                    if (lastChecked != R.id.customized) {
                        changeFragment(TAG_FRAGMENT_CUSTOMIZED);
                        lastChecked = id;
                    }
                }
                break;
            case R.id.shop:
                L.i("shop");
                setEnabled(true, true, true, false, true);
                if (lastChecked != R.id.shop) {
                    changeFragment(TAG_FRAGMENT_SHOP);
                    lastChecked = id;
                }
                break;
//            case R.id.shalo:
//                L.i("shalo");
//                setEnabled(true, true, true, false, true);
//                if (lastChecked != R.id.shalo) {
//                    changeFragment(TAG_FRAGMENT_SHALO);
//                    lastChecked = id;
//                }
//                break;
            case R.id.me:
                L.i("me");
                login = isLogin();
                if (login) {
                    setEnabled(true, true, true, true, false);
                    if (lastChecked != R.id.me) {
                        changeFragment(TAG_FRAGMENT_ME);
                        lastChecked = id;
                    }
                }
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                T.showShort(mContext, "再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNetworkEvent(NetWorkEvent event) {
        if (event.type == NetWorkEvent.UNAVAILABLE) {
            showCustomAlertDialog("网络异常", "开发网络设置?", new CustomAlertDialog.CustomAlertDialogClickListener() {
                @Override
                public void onPositiveButtonClick() {
                    NetUtil.openSetting(MainActivity.this);
                }

                @Override
                public void onNegativeButtonClick() {

                }
            });
        } else if (event.type == NetWorkEvent.AVAILABLE) {
            hideDialog();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLogoutEvent(LogoutEvent event) {
        setEnabled(false, true, true, true, true);
        changeFragment(TAG_FRAGMENT_INDEX);
        lastChecked = R.id.index;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
        EventBus.getDefault().unregister(this);
        System.exit(0);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onError(String code, String msg) {

    }
}
